import Vue from 'vue'
import Router from 'vue-router'
import HomePage from '@/components/home/homePage'
import SquareList from '@/components/square/squareList'
import badMainList from '@/components/badmain/badMainList'
import following from '@/components/following/following'
import getBetter from '@/components/getBetter/getBetter'
import ssq from '@/components/ssq/ssq'
import Login from '@/components/login/login'
import Register from '@/components/register/register'
import { getStorageToken } from '@/config/localUtils'

Vue.use(Router)

const router = new Router({
  routes: [
    // 注册页
    {
      path: '/register',
      name: 'register',
      component: Register
    },
    // 登录页
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    // 内容页
    {
      path: '/',
      name: 'homePage', // 对应:文件里的name属性?
      component: HomePage, // 对应:上面的组件名
      // 默认页面
      redirect: '/badMainList', // 对应:文件里的name属性?
      // 余下所有页面都配置在children中
      children: [{
        path: 'squareList',
        component: SquareList
      }, {
        path: 'badMainList',
        component: badMainList
      }, {
        path: 'following',
        component: following
      }, {
        path: 'getBetter',
        component: getBetter
      }, {
        path: 'ssq',
        component: ssq
      }]
    }
  ]
})
/**
 * 登录拦截
 *
 * 参数1 : to 目标路由对象
 * 参数2 : from 来源路由对象
 * 参数3 : next() 下一步
 */
router.beforeEach((to, from, next) => {
  // 判断是否登录页面
  if (to.path === '/login') {
    next()
  } else if (to.path === '/register') {
    next()
  } else {
    // 获取token
    let token = getStorageToken()
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router